package com.gjy.learning.scala

import org.apache.spark.sql.SparkSession

object Closure2 {
  def main(args: Array[String]): Unit = {
    val spark = SparkSession.builder()
      .appName("VarInClosureExample")
      .master("local[*]")
      .getOrCreate()

    val sc = spark.sparkContext

    var x = 10
    val data = Seq(1, 2, 3, 4, 5)

    val result = sc.parallelize(data).map { num =>
      val localVar = x // 捕获x的副本
      localVar * num
    }.collect()

    println("第一次")
    result.foreach(println)

    x = 20 // 在Driver端修改x

    val newResult = sc.parallelize(data).map { num =>
      val localVar = x // 再次捕获x的副本，但不会感知到之前的修改
      localVar * num
    }.collect()

    println("第二次")
    newResult.foreach(println)

    println("第三次")
    result.foreach(println)


    spark.stop()

  }
}
